package com.alianzamedica.models;

import java.sql.Connection;
import java.sql.PreparedStatement;

import com.alianzamedica.connection.ConnectionImpl;

/**
 * @author carlos
 * 
 */
public class TagWizardModel {

	/**
	 * default constructor
	 */
	public TagWizardModel() {
	}

	/**
	 * guarda todos los tags del asistente para insercion de tags.
	 * 
	 * @param medicId
	 *            id del doctor.
	 * @param lotId
	 *            id del lote a guardar.
	 * @param lotCode
	 *            codigo del lote.
	 * @param tagCodes
	 *            codigos de los tags.
	 * @return verdadero si es correcto, falso si falla.
	 * @throws Exception
	 *             si ocurre error.
	 */
	public boolean saveTags(int medicId, Integer lotId, String lotCode,
			String[] tagCodes) throws Exception {
		boolean success = true;
		String lotInsert = "insert into lot values( ? , ? )";
		String logAssign = "insert into doctor_lot values ( ? , ? )";
		String tagValues = "insert into tag values ( ? , ? , 1 )";
		PreparedStatement psmtInsert = null;
		PreparedStatement psmtAssign = null;
		PreparedStatement psmtTagValues = null;
		ConnectionImpl impl = new ConnectionImpl();
		Connection con = null;
		try {
			impl.open();
			con = impl.getConnection();
			con.setAutoCommit(false);
			psmtInsert = con.prepareStatement(lotInsert);
			psmtInsert.setInt(1, lotId);
			psmtInsert.setString(2, lotCode);
			psmtInsert.execute();
			psmtAssign = con.prepareStatement(logAssign);
			psmtAssign.setInt(1, medicId);
			psmtAssign.setInt(2, lotId);
			psmtAssign.execute();
			psmtTagValues = con.prepareStatement(tagValues);
			int length = tagCodes.length;
			for (int i = 0; i < length; i++) {
				String tagCode = tagCodes[i];
				psmtTagValues.setString(1, tagCode);
				psmtTagValues.setInt(2, lotId);
				psmtTagValues.execute();
			}
			con.commit();
		} catch (Exception e) {
			if (con != null) {
				con.rollback();
				con.setAutoCommit(true);
			}
			e.printStackTrace();
			success = false;
		} finally {
			impl.closeGracefully(psmtInsert);
			impl.closeGracefully(psmtAssign);
			impl.closeGracefully(psmtTagValues);
			try {
				impl.close();
			} catch (Exception e) {
			}
		}
		return success;
	}

}
